package com.xzx.springbootredis.controller;

import com.xzx.springbootredis.entity.Goods;
import com.xzx.springbootredis.service.GoodsService;
import com.xzx.springbootredis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Goods goods;
    //列表
    @GetMapping("lists")
    public JsonResult lists() {
        return JsonResult.success("获取成功",null);
    }
    //商品新增
    @PostMapping("save")
    public JsonResult save(@RequestBody Goods goods) {
        String title = goods.getTitle();
        if (title == null || title.isEmpty()) {
            return JsonResult.failed("商品名不能为空");
        }
        //商品名不能重复
        Goods goodsInfo = goodsService.findByTitle(title);
        if (goodsInfo != null) {
            return JsonResult.failed("该商品名已经存在.");
        }
        if (goods.getContent() == null || goods.getContent().isEmpty()) {
            return JsonResult.failed("商品详情为空");
        }
        if (goods.getPrice() == 0) {
            return JsonResult.failed("商品价格不能为空");
        }
        String id = String.valueOf(goodsService.save(goods));
        //同步到redis,哈希
        Map<String, Object> goodsMap = new HashMap<>();
        goodsMap.put("id", id);
        goodsMap.put("title", goods.getTitle());
        goodsMap.put("content", goods.getContent());
        String price = String.valueOf(goods.getPrice());
        goodsMap.put("price", price);
        System.out.println(goodsMap);
        stringRedisTemplate.opsForHash().putAll("goods:"+id,goodsMap);
        return JsonResult.success("添加成功",id);
    }

    //根据id根据商品
    @GetMapping("details")
    public JsonResult details(@RequestParam("id") int id) {
        //判断缓存里面是不是有数据
        String key = "goods:" + id;
        Object cacheId = stringRedisTemplate.opsForHash().get(key, "id");
        if (stringRedisTemplate.opsForHash().get(key, "title") != null) {
            Map<String, Object> goodsMap = new HashMap<>();
            goodsMap.put("id", id);
            goodsMap.put("title", stringRedisTemplate.opsForHash().get(key, "title"));
            goodsMap.put("content", stringRedisTemplate.opsForHash().get(key, "content"));
            goodsMap.put("price", stringRedisTemplate.opsForHash().get(key, "price"));
            System.out.println(goodsMap);

            return JsonResult.success("获取成功",goodsMap);
        }

        //读db
        Optional<Goods> goodsInfo = goodsService.findById(id);
        return JsonResult.success("ok",goodsInfo);
    }
}
